import { ref, reactive } from 'vue';
import { onPageScroll } from '@dcloudio/uni-app';
import { getSelectorData } from '@/utils';

export default function() {
	// 滚动页面距离
	const pageScrollTop = ref<number>(0);
	// 元素初始距离
	const elementInitPageTop = reactive<any>({
		// 产品
		product: 0,
		// 评价
		evaluate: 0,
		// 详情
		detail: 0,
		// 推荐
		recommend: 0,
	});
	// 获取页面元素的距离顶部的距离
	const getElementPageTop = async (key: string) => {
		const data = await getSelectorData(`#${key}`);
		// 在这里获取距离页面顶部的距离
		if (data) elementInitPageTop[key] = data.top;
	};
	// 初始化页面元素的距离顶部的距离
	const initElementPageTop = (): void => {
		Object.keys(elementInitPageTop).forEach((key: string) => {
			getElementPageTop(key);
		});
	};
	
	// navbar高度
	const navbarHeight = ref<number>(0);
	// 获取navbar高度
	const getNavbarHeight = async () => {
		const data = await getSelectorData('#navbar');
		// 在这里获取navbar高度
		if (data) navbarHeight.value = data.height;
	};
	
	// 当前标签
	const currentTab = ref<number>(0);
	// 是否点击了tab
	const isClickTab = ref<boolean>(false);
	// 点击tab滚动到具体的位置
	const scrollPage = (index: number) => {
		isClickTab.value = true;
		currentTab.value = index;
		const { product, evaluate, detail, recommend } = elementInitPageTop;
		const scrollTops: Array<number> = [
			product,
			evaluate - navbarHeight.value,
			detail - navbarHeight.value,
			recommend - navbarHeight.value,
		];
		uni.pageScrollTo({ scrollTop: scrollTops[index], duration: 0 });
		setTimeout(() => isClickTab.value = false, 100);
	};
	
	// 页面滚动监听，修改对应的标签
	onPageScroll(({ scrollTop }) => {
		pageScrollTop.value = scrollTop;
		// 防止tab点击事件和page的滚动事件冲突
		if (!isClickTab.value) {
			const top = scrollTop + navbarHeight.value + 1;
			if (top < elementInitPageTop.evaluate) {
				currentTab.value = 0;
			} else if (top >= elementInitPageTop.evaluate && top < elementInitPageTop.detail) {
				currentTab.value = 1;
			} else if (top >= elementInitPageTop.detail && top < elementInitPageTop.recommend) {
				currentTab.value = 2;
			} else if (top >= elementInitPageTop.recommend) {
				currentTab.value = 3;
			}
		}
	});
	
	return {
		currentTab,
		pageScrollTop,
		scrollPage,
		getNavbarHeight,
		initElementPageTop,
	}
}